package com.learn.authorization.service.impl;

import com.learn.authorization.mapper.UserMapper;
import com.learn.authorization.pojo.LoginUser;
import com.learn.authorization.pojo.User;
import com.learn.authorization.service.LoginService;
import com.learn.authorization.utils.JwtUtil;
import com.learn.authorization.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * @author DJJ_F
 * @version 1.0
 * @date 2025/04/07
 * @description
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private AuthenticationManager authenticationManager;
    @Autowired
    private RedisCache redisCache;
    @Override
    public String login(User user) {
        // 未认证的信息
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword());
        // 已认证的信息
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);

        LoginUser loginUser = (LoginUser) authenticate.getPrincipal();
        String userId = loginUser.getUser().getId().toString();
        String token = JwtUtil.createJWT(userId);
        redisCache.setCacheObject("login_" + userId, loginUser, 1, TimeUnit.HOURS);
        return token;
    }

    @Override
    public void logout() {

    }
}
